package com.dmall.graph.bfs;

import com.dmall.graph.Graph;

import java.util.*;

/**
 * @author: xiao1.wang
 * @date: 2022/6/19 15:45
 */
public class SingleSourcePath2 {
    private Graph G;
    private int[] pre;
    private int s;
    private int t;

    public SingleSourcePath2(Graph G, int s, int t) {
        G.validateVertex(s);
        G.validateVertex(t);
        this.G = G;
        this.s = s;
        this.t = t;
        this.pre = new int[G.V()];
        Arrays.fill(this.pre, -1);
        bfs(s);
    }

    private void bfs(int v) {
        pre[v] = v;
        if (v == t) {
            return;
        }
        Queue<Integer> queue = new LinkedList<>();
        queue.add(v);
        while (!queue.isEmpty()) {
            Integer cur = queue.remove();
            for (Integer w : G.adj(cur)) {
                if (pre[w] == -1) {
                    pre[w] = cur;
                    if (w == t) {
                        return;
                    }
                    queue.add(w);
                }
            }
        }
    }

    public boolean isConnected() {
        return pre[t] != -1;
    }

    public ArrayList<Integer> path() {
        ArrayList<Integer> res = new ArrayList<>();
        if (!isConnected()) {
            return res;
        }

        int cur = t;
        while (cur != s) {
            res.add(cur);
            cur = pre[cur];
        }
        res.add(s);
        Collections.reverse(res);
        return res;
    }

    public static void main(String[] args) {
        String filename = SingleSourcePath2.class.getClassLoader().getResource("g.txt").getPath();
        Graph g = new Graph(filename);

        SingleSourcePath2 path1 = new SingleSourcePath2(g, 0, 6);
        System.out.println("0 -> 6 : " + path1.path());

        SingleSourcePath2 path2 = new SingleSourcePath2(g, 0, 1);
        System.out.println("0 -> 1 : " + path2.path());

        SingleSourcePath2 path3 = new SingleSourcePath2(g, 0, 5);
        System.out.println("0 -> 5 : " + path3.path());

        SingleSourcePath2 path4 = new SingleSourcePath2(g, 0, 0);
        System.out.println("0 -> 0 : " + path4.path());
    }
}
